import 'package:efood_multivendor/controller/auth_controller.dart';
import 'package:efood_multivendor/controller/location_controller.dart';
import 'package:efood_multivendor/controller/splash_controller.dart';
import 'package:efood_multivendor/controller/user_controller.dart';
import 'package:efood_multivendor/data/model/response/address_model.dart';
import 'package:efood_multivendor/helper/location_permission.dart';
import 'package:efood_multivendor/helper/route_helper.dart';
import 'package:efood_multivendor/helper/size_config.dart';
import 'package:efood_multivendor/util/dimensions.dart';
import 'package:efood_multivendor/util/images.dart';
import 'package:efood_multivendor/util/styles.dart';
import 'package:efood_multivendor/view/base/custom_app_bar.dart';
import 'package:efood_multivendor/view/base/custom_button.dart';
import 'package:efood_multivendor/view/base/custom_snackbar.dart';
import 'package:efood_multivendor/view/base/my_text_field.dart';
import 'package:efood_multivendor/view/base/not_logged_in_screen.dart';
import 'package:efood_multivendor/view/screens/location/pick_map_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_feather_icons/flutter_feather_icons.dart';
import 'package:get/get.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';

class AddAddressScreen extends StatefulWidget {
  final bool fromCheckout;
  final bool fromEmptyHome;
  final AddressModel? address;
  AddAddressScreen(
      {required this.fromCheckout, this.address, this.fromEmptyHome = false});

  @override
  State<AddAddressScreen> createState() => _AddAddressScreenState();
}

class _AddAddressScreenState extends State<AddAddressScreen> {
  final TextEditingController _addressController = TextEditingController();
  final TextEditingController _contactPersonNameController =
      TextEditingController();
  final TextEditingController _contactPersonNumberController =
      TextEditingController();
  final TextEditingController _lableAsController = TextEditingController();
  final FocusNode _addressNode = FocusNode();
  final FocusNode _lableNode = FocusNode();
  final FocusNode _nameNode = FocusNode();
  final FocusNode _numberNode = FocusNode();
  bool _isLoggedIn = false;
  late CameraPosition _cameraPosition;
  LatLng? _initialPosition;

  @override
  void initState() {
    super.initState();

    _isLoggedIn = Get.find<AuthController>().isLoggedIn();
    if (_isLoggedIn && Get.find<UserController>().userInfoModel == null) {
      Get.find<UserController>().getUserInfo();
    }
    if (widget.address == null) {
      _initialPosition = LatLng(
        double.parse(
            Get.find<SplashController>().configModel?.defaultLocation?.lat ??
                '0'),
        double.parse(
            Get.find<SplashController>().configModel?.defaultLocation?.lng ??
                '0'),
      );
    } else {
      Get.find<LocationController>().setUpdateAddress(widget.address!);
      _initialPosition = LatLng(
        double.parse(widget.address?.latitude ?? '0'),
        double.parse(widget.address?.longitude ?? '0'),
      );
    }
    _cameraPosition = CameraPosition(
      target: _initialPosition!,
      zoom: 17,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CustomAppBar(
        title:
            widget.address == null ? 'add_new_address'.tr : 'update_address'.tr,
        onBackPressed: () {
          Get.back();
        },
      ),
      body: _isLoggedIn
          ? GetBuilder<UserController>(builder: (userController) {
              if (widget.address != null) {
                if (_contactPersonNameController.text.isEmpty) {
                  _contactPersonNameController.text =
                      widget.address?.contactPersonName ?? '';
                  _contactPersonNumberController.text =
                      widget.address?.contactPersonNumber ?? '';
                }
              } else if (userController.userInfoModel != null &&
                  _contactPersonNameController.text.isEmpty) {
                _contactPersonNameController.text =
                    '${userController.userInfoModel?.fName ?? ''}';
                _contactPersonNumberController.text =
                    userController.userInfoModel?.phone ?? '';
              }

              return GetBuilder<LocationController>(
                  builder: (locationController) {
                _addressController.text = locationController.address;

                return Column(children: [
                  Expanded(
                      child: Scrollbar(
                          child: SingleChildScrollView(
                    physics: BouncingScrollPhysics(),
                    padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
                    child: Center(
                        child: SizedBox(
                            width: Dimensions.WEB_MAX_WIDTH,
                            child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                children: [
                                  Container(
                                    height: 140,
                                    width: MediaQuery.of(context).size.width,
                                    decoration: BoxDecoration(
                                      borderRadius: BorderRadius.circular(
                                          Dimensions.RADIUS_SMALL),
                                      border: Border.all(
                                          width: 2,
                                          color:
                                              Theme.of(context).primaryColor),
                                    ),
                                    child: ClipRRect(
                                      borderRadius: BorderRadius.circular(
                                          Dimensions.RADIUS_SMALL),
                                      child: Stack(
                                          clipBehavior: Clip.none,
                                          children: [
                                            GoogleMap(
                                              initialCameraPosition:
                                                  CameraPosition(
                                                      target: _initialPosition!,
                                                      zoom: 17),
                                              onTap: (latLng) {
                                                Get.toNamed(
                                                  RouteHelper.getPickMapRoute(
                                                      'add-address', false),
                                                  arguments: PickMapScreen(
                                                    fromAddAddress: true,
                                                    fromSignUp: false,
                                                    googleMapController:
                                                        locationController
                                                            .mapController,
                                                    route: '',
                                                    canRoute: false,
                                                  ),
                                                );
                                              },
                                              zoomControlsEnabled: false,
                                              compassEnabled: false,
                                              indoorViewEnabled: true,
                                              mapToolbarEnabled: false,
                                              myLocationButtonEnabled: false,
                                              onCameraIdle: () async {
                                                if (locationController
                                                        .cameraPosition !=
                                                    null) {
                                                  await locationController
                                                      .updatePosition(
                                                          locationController
                                                              .cameraPosition!,
                                                          true);
                                                } else {
                                                  await locationController
                                                      .updatePosition(
                                                          _cameraPosition,
                                                          true);
                                                }
                                              },
                                              onCameraMove: ((position) =>
                                                  _cameraPosition = position),
                                              onMapCreated: (GoogleMapController
                                                  controller) {
                                                locationController
                                                    .setMapController(
                                                        controller);
                                                if (widget.address == null) {
                                                  locationController
                                                      .getCurrentLocation(true,
                                                          mapController:
                                                              controller);
                                                }
                                              },
                                            ),
                                            locationController.loading
                                                ? Center(
                                                    child:
                                                        CircularProgressIndicator
                                                            .adaptive(
                                                      backgroundColor:
                                                          Theme.of(context)
                                                              .colorScheme
                                                              .secondary,
                                                    ),
                                                  )
                                                : SizedBox(),
                                            Center(
                                              child: !locationController.loading
                                                  ? Image.asset(
                                                      Images.pick_marker,
                                                      height: 50,
                                                      width: 50)
                                                  : CircularProgressIndicator
                                                      .adaptive(
                                                      backgroundColor:
                                                          Theme.of(context)
                                                              .colorScheme
                                                              .secondary,
                                                    ),
                                            ),
                                            Positioned(
                                              bottom: 10,
                                              right: 0,
                                              child: InkWell(
                                                onTap: () =>
                                                    LocationPermissionHelper
                                                        .checkPermission(() {
                                                  locationController
                                                      .getCurrentLocation(true,
                                                          mapController:
                                                              locationController
                                                                  .mapController);
                                                }),
                                                child: Container(
                                                  width: 30,
                                                  height: 30,
                                                  margin: EdgeInsets.only(
                                                      right: Dimensions
                                                          .PADDING_SIZE_LARGE),
                                                  decoration: BoxDecoration(
                                                      borderRadius: BorderRadius
                                                          .circular(Dimensions
                                                              .RADIUS_SMALL),
                                                      color: Colors.white),
                                                  child: Icon(Icons.my_location,
                                                      color: Theme.of(context)
                                                          .primaryColor,
                                                      size: 20),
                                                ),
                                              ),
                                            ),
                                            Positioned(
                                              top: 10,
                                              right: 0,
                                              child: InkWell(
                                                onTap: () {
                                                  Get.toNamed(
                                                    RouteHelper.getPickMapRoute(
                                                        'add-address', false),
                                                    arguments: PickMapScreen(
                                                      fromAddAddress: true,
                                                      fromSignUp: false,
                                                      googleMapController:
                                                          locationController
                                                              .mapController,
                                                      route: '',
                                                      canRoute: false,
                                                    ),
                                                  );
                                                },
                                                child: Container(
                                                  width: 30,
                                                  height: 30,
                                                  margin: EdgeInsets.only(
                                                      right: Dimensions
                                                          .PADDING_SIZE_LARGE),
                                                  decoration: BoxDecoration(
                                                      borderRadius: BorderRadius
                                                          .circular(Dimensions
                                                              .RADIUS_SMALL),
                                                      color: Colors.white),
                                                  child: Icon(Icons.fullscreen,
                                                      color: Theme.of(context)
                                                          .primaryColor,
                                                      size: 20),
                                                ),
                                              ),
                                            ),
                                          ]),
                                    ),
                                  ),
                                  SizedBox(
                                      height: Dimensions.PADDING_SIZE_SMALL),
                                  Center(
                                      child: Text(
                                    'add_the_location_correctly'.tr,
                                    style: sfRegular.copyWith(
                                        color: Theme.of(context).disabledColor,
                                        fontSize:
                                            Dimensions.fontSizeExtraSmall),
                                  )),
                                  SizedBox(
                                      height: Dimensions.PADDING_SIZE_LARGE),
                                  Text(
                                    'label_as'.tr,
                                    style: sfRegular.copyWith(
                                        fontSize: Dimensions.fontSizeSmall,
                                        color: Theme.of(context).disabledColor),
                                  ),
                                  SizedBox(
                                      height: Dimensions.PADDING_SIZE_SMALL),
                                  SizedBox(
                                      height: 13.h,
                                      child: Center(
                                        child: ListView.builder(
                                          shrinkWrap: true,
                                          scrollDirection: Axis.horizontal,
                                          itemCount: locationController
                                                  .addressTypeList.length -
                                              1,
                                          itemBuilder: (context, index) =>
                                              InkWell(
                                            onTap: () {
                                              locationController
                                                  .setAddressTypeIndex(index);
                                            },
                                            child: Center(
                                              child: Container(
                                                width: 13.h,
                                                height: 13.h,
                                                padding: EdgeInsets.symmetric(
                                                    horizontal: Dimensions
                                                        .PADDING_SIZE_LARGE,
                                                    vertical: Dimensions
                                                        .PADDING_SIZE_SMALL),
                                                margin: EdgeInsets.only(
                                                    right: Dimensions
                                                        .PADDING_SIZE_SMALL),
                                                decoration: BoxDecoration(
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                          Dimensions
                                                              .RADIUS_SMALL),
                                                  gradient: locationController
                                                              .addressTypeIndex ==
                                                          index
                                                      ? LinearGradient(
                                                          colors: [
                                                            Theme.of(context)
                                                                .primaryColor,
                                                            Theme.of(context)
                                                                .colorScheme
                                                                .secondary
                                                          ],
                                                        )
                                                      : LinearGradient(
                                                          colors: [
                                                            Colors.white,
                                                            Colors.white
                                                          ],
                                                        ),
                                                  boxShadow: [
                                                    BoxShadow(
                                                        color: Colors.grey[
                                                            Get.isDarkMode
                                                                ? 800
                                                                : 200]!,
                                                        spreadRadius: 1,
                                                        blurRadius: 5)
                                                  ],
                                                ),
                                                child: Column(
                                                    mainAxisAlignment:
                                                        MainAxisAlignment
                                                            .center,
                                                    children: [
                                                      Icon(
                                                          index == 0
                                                              ? FeatherIcons
                                                                  .home
                                                              : index == 1
                                                                  ? FeatherIcons
                                                                      .briefcase
                                                                  : FeatherIcons
                                                                      .flag,
                                                          size: 4.h,
                                                          color: locationController
                                                                      .addressTypeIndex ==
                                                                  index
                                                              ? Colors.white
                                                              : Theme.of(
                                                                      context)
                                                                  .textTheme
                                                                  .bodyMedium
                                                                  ?.color),
                                                      SizedBox(
                                                          width: Dimensions
                                                              .PADDING_SIZE_EXTRA_SMALL),
                                                      Text(
                                                        locationController
                                                            .addressTypeList[
                                                                index]
                                                            .tr,
                                                        style: sfRegular.copyWith(
                                                            color: locationController
                                                                        .addressTypeIndex ==
                                                                    index
                                                                ? Colors.white
                                                                : Theme.of(
                                                                        context)
                                                                    .textTheme
                                                                    .bodyMedium
                                                                    ?.color,
                                                            fontSize: Dimensions
                                                                    .fontSizeExtraLarge *
                                                                0.25.w),
                                                      ),
                                                    ]),
                                              ),
                                            ),
                                          ),
                                        ),
                                      )),
                                  SizedBox(
                                      height: Dimensions.PADDING_SIZE_LARGE),
                                  locationController.addressTypeIndex == 2
                                      ? MyTextField(
                                          hintText: 'label_as'.tr,
                                          inputType: TextInputType.text,
                                          focusNode: _lableNode,
                                          nextFocus: _addressNode,
                                          controller: _lableAsController,
                                          onChanged: (text) => {})
                                      : SizedBox(
                                          height:
                                              Dimensions.PADDING_SIZE_LARGE),
                                  Text(
                                    'delivery_address'.tr,
                                    style: sfRegular.copyWith(
                                        fontSize: Dimensions.fontSizeSmall,
                                        color: Theme.of(context).disabledColor),
                                  ),
                                  SizedBox(
                                      height: Dimensions.PADDING_SIZE_SMALL),
                                  MyTextField(
                                    hintText: 'delivery_address'.tr,
                                    inputType: TextInputType.streetAddress,
                                    focusNode: _addressNode,
                                    nextFocus: _nameNode,
                                    controller: _addressController,
                                    onChanged: (text) =>
                                        locationController.setPlaceMark(text),
                                  ),
                                  SizedBox(
                                      height: Dimensions.PADDING_SIZE_LARGE),
                                  Text(
                                    'contact_person_name'.tr,
                                    style: sfRegular.copyWith(
                                        fontSize: Dimensions.fontSizeSmall,
                                        color: Theme.of(context).disabledColor),
                                  ),
                                  SizedBox(
                                      height: Dimensions.PADDING_SIZE_SMALL),
                                  MyTextField(
                                    hintText: 'contact_person_name'.tr,
                                    inputType: TextInputType.name,
                                    controller: _contactPersonNameController,
                                    focusNode: _nameNode,
                                    nextFocus: _numberNode,
                                    capitalization: TextCapitalization.words,
                                  ),
                                  SizedBox(
                                      height: Dimensions.PADDING_SIZE_LARGE),
                                  Text(
                                    'contact_person_number'.tr,
                                    style: sfRegular.copyWith(
                                        fontSize: Dimensions.fontSizeSmall,
                                        color: Theme.of(context).disabledColor),
                                  ),
                                  SizedBox(
                                      height: Dimensions.PADDING_SIZE_SMALL),
                                  MyTextField(
                                    hintText: 'contact_person_number'.tr,
                                    inputType: TextInputType.phone,
                                    inputAction: TextInputAction.done,
                                    focusNode: _numberNode,
                                    controller: _contactPersonNumberController,
                                  ),
                                  SizedBox(
                                      height: Dimensions.PADDING_SIZE_LARGE),
                                ]))),
                  ))),
                  Container(
                    width: Dimensions.WEB_MAX_WIDTH,
                    padding: EdgeInsets.all(Dimensions.PADDING_SIZE_SMALL),
                    child: !locationController.isLoading
                        ? SafeArea(
                            child: CustomButton(
                              buttonText: widget.address == null
                                  ? 'save_location'.tr
                                  : 'update_address'.tr,
                              onPressed: locationController.loading
                                  ? null
                                  : () async {
                                      AddressModel _addressModel = AddressModel(
                                        id: widget.address != null
                                            ? widget.address?.id
                                            : null,
                                        addressType: locationController
                                                    .addressTypeIndex ==
                                                2
                                            ? _lableAsController.text
                                            : locationController
                                                    .addressTypeList[
                                                locationController
                                                    .addressTypeIndex],
                                        contactPersonName:
                                            _contactPersonNameController.text,
                                        contactPersonNumber:
                                            _contactPersonNumberController.text,
                                        address: _addressController.text,
                                        latitude: locationController
                                            .position.latitude
                                            .toString(),
                                        longitude: locationController
                                            .position.longitude
                                            .toString(),
                                        zoneId: locationController.zoneID,
                                      );

                                      if (widget.address == null) {
                                        locationController
                                            .addAddress(_addressModel,
                                                widget.fromCheckout)
                                            .then((response) async {
                                          if (response.isSuccess) {
                                            if (widget.fromEmptyHome) {
                                              Get.toNamed(
                                                  RouteHelper.getInitialRoute(
                                                      "SplashScreen"));
                                            } else {
                                              Get.back();
                                            }

                                            showCustomSnackBar(
                                                'new_address_added_successfully'
                                                    .tr,
                                                isError: false);
                                          } else {
                                            showCustomSnackBar(
                                                response.message);
                                          }
                                        });
                                      } else {
                                        locationController
                                            .updateAddress(_addressModel,
                                                widget.address!.id!)
                                            .then((response) {
                                          if (response.isSuccess) {
                                            Get.back();

                                            showCustomSnackBar(response.message,
                                                isError: false);
                                          } else {
                                            showCustomSnackBar(
                                                response.message);
                                          }
                                        });
                                      }
                                    },
                            ),
                          )
                        : Center(
                            child: CircularProgressIndicator.adaptive(
                              backgroundColor:
                                  Theme.of(context).colorScheme.secondary,
                            ),
                          ),
                  ),
                ]);
              });
            })
          : NotLoggedInScreen(),
    );
  }
}
